package com.itheima.pinda.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 用于操作Kafka
 *
 * @author llhuang10
 * @date 2021/10/21 8:50
 */
@Slf4j
@Component
public class KafkaSender {

    /**
     * kafka队列名称
     */
    public static final String MSG_TOPIC = "tms_order_location";

    private static KafkaTemplate<String, String> template;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 向kafka队列发送消息
     *
     * @param topic   topic
     * @param message 消息内容
     * @return 是否发送成功
     */
    public static boolean send(String topic, String message) {
        try {
            template.send(topic, message);
            log.info("消息发送成功：{} , {}", topic, message);
            return true;
        } catch (Exception e) {
            log.error("消息发送失败：{} , {}", topic, message, e);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 为静态的template类变量赋值
     */
    @PostConstruct
    public void init() {
        template = this.kafkaTemplate;
    }
}
